package ebj.common.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import ebj.common.domain.Person;
import ebj.common.utils.Utils;

/**
 * 反射实例4：通过Class调用其他类中的构造函数 （也可以通过这种方式通过Class创建其他类的对象）
 * 另一种方式
 * @author zhouxiangyong
 * @version $Id$
 */
public class ReflectClient4 {
	public static void main(String[] args) {
		String clazzName = Utils.getProperty("Person");
		Class<?> clazz = null;
		
		try {
			clazz = Class.forName(clazzName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		Constructor<?>[] constructors = clazz.getConstructors();
		for (Constructor<?> constructor : constructors) {
			try {
				Class<?>[] clazzes = constructor.getParameterTypes();
				int parmsNum = clazzes.length;
				Person person = null;
				if (parmsNum == 0) {
					person = (Person) constructor.newInstance();
					person.setAge(11);
					person.setName("Ada");
				}else if (parmsNum == 1) {
					String parmType = clazzes[0].getSimpleName();
					if ("int".equals(parmType)) {
						person = (Person) constructor.newInstance(15);
						person.setName("Alice");
					}else if ("String".equals(parmType)) {
						person = (Person) constructor.newInstance("Martin");
						person.setAge(16);
					}
				}else if (parmsNum == 2) {
					person = (Person) constructor.newInstance("Jack", 20);
				}
				System.out.println(person);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}
}
